package co.example.michael.tools;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

import co.example.michael.application.CustomApplication;
import co.example.michael.bigpictureloading.FinalConstant;
import libcore.io.DiskLruCache;

/**
 * Created by Michael on 2015/3/18.
 */
public class PictureAllTools {

    private final static String TAG = "PictureAllTools";
    public PictureAllTools(){}

    /**
     * 根据路径给ImageView控件设置图片
     * @param path
     */
    public static void setImageView(ImageView imageView,String path){
        int degree = PictureAllTools.getRotateBitmapDegree(path);
        Bitmap bitmap = PictureAllTools.getBitmapFromPath(path);

        bitmap = PictureAllTools.getRotateBitmap(bitmap, degree);

        imageView.setImageBitmap(bitmap);
    }

    /**
     * 从图片Uri中解析出图片的物理路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getPathFromUri(Context context, Uri uri) {
        ContentResolver contentResolver = context.getContentResolver();

        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        int index = cursor.getColumnIndex("_data");
        cursor.moveToFirst();
        String path = cursor.getString(index);
        return path;
    }


    /**
     * 从手机sd路径读取图片，并压缩大小
     * @param path
     * @return
     */
    public static Bitmap getBitmapFromPath(String path){

        FileInputStream inputStream;

        Bitmap bitmap = null;
        try{
            inputStream = new FileInputStream(new File(path));

            BitmapFactory.Options options = new BitmapFactory.Options();

            options.inJustDecodeBounds = true;

            //将图片的信息保存到options中
            BitmapFactory.decodeFile(path,options);

            //获得压缩比例
            int be = 1;
            if (options.outHeight > FinalConstant.IMAGEVIEW_HEIGHT || options.outWidth > FinalConstant.IMAGEVIEW_WIDTH){
                int bH = options.outHeight / FinalConstant.IMAGEVIEW_HEIGHT;
                int bW = options.outWidth / FinalConstant.IMAGEVIEW_WIDTH;

                be = bH>bW ? bH : bW;
            }

            options.inSampleSize = be;

            options.inJustDecodeBounds = false;

            //设置色彩模式，防止OOM
            options.inPreferredConfig = Bitmap.Config.RGB_565;

            options.inPurgeable = true;

            options.inInputShareable = true;

            bitmap = BitmapFactory.decodeStream(inputStream,null,options);

            return bitmap;

        }catch (Exception e){
            e.printStackTrace();
        }

        return bitmap;
    }

    /**
     * 获得相册中照片的旋转角度
     * @param path
     * @return
     */
    public  static int getRotateBitmapDegree(String path){
        int degree = 0;
        try{
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
            switch (orientation){
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 按照旋转角度，得到旋转后的Bitmap
     * @param bitmap
     * @param degree
     * @return
     */
    public static Bitmap getRotateBitmap(Bitmap bitmap,int degree){

        Matrix matrix = new Matrix();
        matrix.postRotate(degree);

        Bitmap b = bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);

        return b;
    }

    /**
     * 根据key从内存中读取图片
     * @param key 图片的url
     * @return
     */
    public static Bitmap getBitmapFromMemoryCache(String key){
        return CustomApplication.lruCache.get(key);
    }

    /**
     * 给内存中缓存图片
     * @param bitmap
     * @param key  LruCache的键，这里传入图片的URL地址。
     */
    public static void addBitmapToMemoryCache(Bitmap bitmap,String key){
        if (CustomApplication.lruCache.get(key)==null){
            CustomApplication.lruCache.put(key,bitmap);
        }
    }

    /**
     * 根据图片的url生成MD5的key,这样做可以得到独一无二的key,并且不会出现乱码
     * @param url
     * @return
     */
    private static String getPictureMD5Key(String url){
        String cacheKey = "";
        try{
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(url.getBytes());
            cacheKey = bytesToHexString(messageDigest.digest());

        }catch (Exception e){
            cacheKey = String.valueOf(url.hashCode());
         }
        return cacheKey;
    }

    /**
     * 生成MD5的辅助方法
     * @param bytes
     * @return
     */
    private static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 从sd卡图片缓存中获取图片
     * @param url  图片的url
     * @return
     */
    public static Bitmap getBitmapFromDisk(String url){

        //生成图片url对应的MD5key
        String cacheKey = getPictureMD5Key(url);
        Bitmap bitmap = null;
        try{
            DiskLruCache.Snapshot snapshot = CustomApplication.diskLruCache.get(cacheKey);
            if (snapshot == null){
                bitmap = null;
            }else {
                InputStream inputStream = snapshot.getInputStream(0);
                bitmap = BitmapFactory.decodeStream(inputStream);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 从网络上下载图片，并保存到sd卡缓存区和内存中
     * @param url
     */
    public static void addBitmapToDiskAndMemory(String url){

        //得到url对应的key
        String cacheKey = getPictureMD5Key(url);
        try{
            // 如果没有找到对应的缓存，则准备从网络上请求数据，并写入缓存
            DiskLruCache.Editor editor = CustomApplication.diskLruCache.edit(cacheKey);
            if (editor != null) {
                OutputStream outputStream = editor.newOutputStream(0);
                if (downloadUrlToStream(url, outputStream)) {

                    editor.commit();

                    //保存到内存中
                    Bitmap bitmap = getBitmapFromDisk(url);
                    if (bitmap!=null){
                        addBitmapToMemoryCache(bitmap,url);
                    }else {
                        Log.e(TAG,"addBitmapToDiskAndMemory方法："+"图片没有保存成功");
                    }
                } else {
                    editor.abort();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 从网络上下载图片 并存储在输出流outputStream中
     * @param urlString
     * @param outputStream
     * @return
     */
    private static boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
            out = new BufferedOutputStream(outputStream, 8 * 1024);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
